<html lang="zh-CN"><head><meta charset="UTF-8"><style>.nodata  main {width:1000px;margin: auto;}</style></head><body class="nodata " style=""><div class="main_father clearfix d-flex justify-content-center " style="height:100%;"> <div class="container clearfix " id="mainBox"><main><div class="blog-content-box">
<div class="article-header-box">
<div class="article-header">
<div class="article-title-box">
<h1 class="title-article" id="articleContentId">(A卷,100分)- 积木最远距离（Java & JS & Python）</h1>
</div>
</div>
</div>
<div id="blogHuaweiyunAdvert"></div>

        <div id="article_content" class="article_content clearfix">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/kdoc_html_views-1a98987dfd.css">
        <link rel="stylesheet" href="https://csdnimg.cn/release/blogv2/dist/mdeditor/css/editerView/ck_htmledit_views-044f2cf1dc.css">
                <div id="content_views" class="htmledit_views">
                    <h4 id="main-toc">题目描述</h4> 
<p>小华和小薇一起通过玩积木游戏学习数学。<br /> 他们有很多积木&#xff0c;每个积木块上都有一个数字&#xff0c;积木块上的数字可能相同。<br /> 小华随机拿一些积木挨着排成一排&#xff0c;请小薇找到这排积木中数字相同且所处位置最远的2块积木块&#xff0c;计算他们的距离&#xff0c;小薇请你帮忙替她解决这个问题。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%85%A5%E6%8F%8F%E8%BF%B0">输入描述</h4> 
<p>第一行输入为N&#xff0c;表示小华排成一排的积木总数。<br /> 接下来N行每行一个数字&#xff0c;表示小华排成一排的积木上数字。</p> 
<p></p> 
<h4 id="%E8%BE%93%E5%87%BA%E6%8F%8F%E8%BF%B0">输出描述</h4> 
<p>相同数字的积木的位置最远距离&#xff1b;如果所有积木数字都不相同&#xff0c;请返回-1。</p> 
<p></p> 
<h4>备注</h4> 
<ul><li>0&lt;&#61;积木上的数字&lt;10^9</li><li>1&lt;&#61;积木长度&lt;&#61;10^5</li></ul> 
<p></p> 
<h4 id="%E7%94%A8%E4%BE%8B">用例</h4> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">5<br /> 1<br /> 2<br /> 3<br /> 1<br /> 4</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">3</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">共有5个积木&#xff0c;第1个积木和第4个积木数字相同&#xff0c;其距离为3。</td></tr></tbody></table> 
<table border="1" cellpadding="1" cellspacing="1" style="width:500px;"><tbody><tr><td style="width:86px;">输入</td><td style="width:412px;">2<br /> 1<br /> 2</td></tr><tr><td style="width:86px;">输出</td><td style="width:412px;">-1</td></tr><tr><td style="width:86px;">说明</td><td style="width:412px;">一共有两个积木&#xff0c;没有积木数字相同&#xff0c;返回-1。</td></tr></tbody></table> 
<h4 id="%E9%A2%98%E7%9B%AE%E8%A7%A3%E6%9E%90">题目解析</h4> 
<p>这题第一眼看上去好像是要用双指针做&#xff0c;但是实操起来却不行。</p> 
<p>这题的数组长度会达到10^5&#xff0c;因此时间复杂度要至少控制在O(n)。</p> 
<p></p> 
<p>我的解题思路如下&#xff1a;</p> 
<p>定义一个idx对象&#xff0c;用于存放每个num出现的索引位置&#xff0c;num作为idx对象属性&#xff0c;num出现的索引位置作为idx[num]的数组的元素。</p> 
<p>然后遍历nums数组&#xff08;即从第二行开始输入的数的集合&#xff09;&#xff0c;开始录入num的索引位置到idx对象中。</p> 
<p></p> 
<p>统计完后&#xff0c;开始遍历idx对象属性&#xff0c;即每个num&#xff0c;然后先判断idx[num]的数组长度是否大于1&#xff0c;若不大于&#xff0c;则不考虑&#xff0c;若大于&#xff0c;则用idx[num]数组的最后一个索引位置 减去 idx[num]数组的第一个索引位置。按照上面逻辑&#xff0c;计算出最大的索引差作为题解。</p> 
<p>若没有符合要求的&#xff0c;则返回-1。</p> 
<p></p> 
<h4 id="%E7%AE%97%E6%B3%95%E6%BA%90%E7%A0%81">JavaScript算法源码</h4> 
<pre><code class="language-javascript">/* JavaScript Node ACM模式 控制台输入获取 */
const readline &#61; require(&#34;readline&#34;);

const rl &#61; readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

const lines &#61; [];
let n;
rl.on(&#34;line&#34;, (line) &#61;&gt; {
  lines.push(line);

  if (lines.length &#61;&#61;&#61; 1) {
    n &#61; lines[0] - 0;
  }

  if (n &amp;&amp; lines.length &#61;&#61;&#61; n &#43; 1) {
    lines.shift();
    const arr &#61; lines.map(Number);
    console.log(getResult(arr));

    lines.length &#61; 0;
  }
});

function getResult(nums) {
  const idx &#61; {};

  for (let i &#61; 0; i &lt; nums.length; i&#43;&#43;) {
    const num &#61; nums[i];
    idx[num] ? idx[num].push(i) : (idx[num] &#61; [i]);
  }

  let ans &#61; -1;
  for (let k in idx) {
    if (idx[k].length &gt; 1) {
      ans &#61; Math.max(ans, idx[k].at(-1) - idx[k][0]);
    }
  }

  return ans;
}
</code></pre> 
<p></p> 
<h4>Java算法源码</h4> 
<pre><code class="language-java">import java.util.HashMap;
import java.util.LinkedList;
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc &#61; new Scanner(System.in);

    int n &#61; sc.nextInt();

    int[] arr &#61; new int[n];
    for (int i &#61; 0; i &lt; n; i&#43;&#43;) {
      arr[i] &#61; sc.nextInt();
    }

    System.out.println(getResult(arr));
  }

  public static int getResult(int[] arr) {
    HashMap&lt;Integer, LinkedList&lt;Integer&gt;&gt; idx &#61; new HashMap&lt;&gt;();

    for (int i &#61; 0; i &lt; arr.length; i&#43;&#43;) {
      int num &#61; arr[i];
      idx.putIfAbsent(num, new LinkedList&lt;&gt;());
      idx.get(num).add(i);
    }

    int ans &#61; -1;

    for (Integer k : idx.keySet()) {
      LinkedList&lt;Integer&gt; link &#61; idx.get(k);
      if (link.size() &gt; 1) {
        ans &#61; Math.max(ans, link.getLast() - link.getFirst());
      }
    }

    return ans;
  }
}
</code></pre> 
<p></p> 
<h4>Python算法源码</h4> 
<pre><code class="language-python"># 输入获取
n &#61; int(input())
arr &#61; []
for i in range(n):
    arr.append(int(input()))


# 算法入口
def getResult(arr, n):
    idx &#61; {}

    for i in range(n):
        num &#61; arr[i]
        if idx.get(num) is None:
            idx[num] &#61; [i]
        else:
            idx[num].append(i)

    ans &#61; -1
    for k in idx.keys():
        if len(idx[k]) &gt; 1:
            ans &#61; max(ans, idx[k][-1] - idx[k][0])

    return ans


# 算法调用
print(getResult(arr, n))
</code></pre>
                </div>
        </div>
        <div id="treeSkill"></div>
        <div id="blogExtensionBox" style="width:400px;margin:auto;margin-top:12px" class="blog-extension-box"></div>
    <script>
  $(function() {
    setTimeout(function () {
      var mathcodeList = document.querySelectorAll('.htmledit_views img.mathcode');
      if (mathcodeList.length > 0) {
        for (let i = 0; i < mathcodeList.length; i++) {
          if (mathcodeList[i].naturalWidth === 0 || mathcodeList[i].naturalHeight === 0) {
            var alt = mathcodeList[i].alt;
            alt = '\\(' + alt + '\\)';
            var curSpan = $('<span class="img-codecogs"></span>');
            curSpan.text(alt);
            $(mathcodeList[i]).before(curSpan);
            $(mathcodeList[i]).remove();
          }
        }
        MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
      }
    }, 1000)
  });
</script>
</div></html>